package com.dj.ms.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.dj.common.request.BuCentralRequest;
import com.dj.common.request.CentralPageRequest;
import com.dj.common.request.CentralRequest;
import com.dj.ms.session.Principal;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 设置上下文Principal至原请求对象
 *
 * @author ZJG
 * @version 1.0
 * @date 2022/02/21 16:34
 */
public class PrincipalSetUtils {

    public static void setCentralRequest(Object object, Principal principal) {
        if (object instanceof BuCentralRequest) {
            BuCentralRequest buCentralRequest = (BuCentralRequest) object;
            //找到CentralBuRequest已有值的属性名集合数组
            String[] ignoreProperties = getNotEmptyFields(buCentralRequest, object.getClass().getSuperclass());
            //非空字段不覆盖设置
            BeanUtil.copyProperties(principal, buCentralRequest, CopyOptions.create().setIgnoreNullValue(true).setIgnoreProperties(ignoreProperties).setIgnoreError(true));
        } else if (object instanceof CentralRequest) {
            CentralRequest centralRequest = (CentralRequest) object;
            //找到centralRequest已有值的属性名集合数组
            Class<?> baseParentClazz = object instanceof CentralPageRequest ? object.getClass().getSuperclass().getSuperclass() : object.getClass().getSuperclass();
            String[] ignoreProperties = getNotEmptyFields(centralRequest, baseParentClazz);
            //非空字段不覆盖设置
            BeanUtil.copyProperties(principal, centralRequest, CopyOptions.create().setIgnoreNullValue(true).setIgnoreProperties(ignoreProperties).setIgnoreError(true));
        }
    }

    private static String[] getNotEmptyFields(Object obj, Class<?> clazz) {
        //得到属性集合
        Field[] fs = clazz.getDeclaredFields();
        List<String> ignoreProperties = new ArrayList<>();
        try {
            //遍历属性
            for (Field field : fs) {
                //设置属性是可以访问的（私有的也可以）
                field.setAccessible(true);
                Object fieldObj = field.get(obj);
                if (ObjectUtil.isNotEmpty(fieldObj)) {
                    ignoreProperties.add(field.getName());
                }
            }
        } catch (Exception e) {
            return null;
        }
        String[] propers = new String[ignoreProperties.size()];
        return ignoreProperties.toArray(propers);
    }
}
